package com.landmesure.utils;

import com.util.ByteUtil;
import com.util.DateTimeUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PropertyBuilderOfDateTime implements PropertyBuilder {
	
	private final static SimpleDateFormat df(){ return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");}
	private final static SimpleDateFormat ef(){ return new SimpleDateFormat("yyMMddHHmmss");}
	

	@Override
	public short[] buildProperty(int code, int len,String value) throws ParseException {
		short [] dateByte = new short[7];
		dateByte[0]=(byte)code;

		Date rtime = DateTimeUtil.YYMMddHHmmss().parse(value);
		String rtimeString = ByteUtil.dateToBcdString(rtime);
		byte[] datebuffer = new byte[6];
		datebuffer[0] = (byte)Integer.parseInt(rtimeString.substring(0,2));
		datebuffer[1] = (byte)Integer.parseInt(rtimeString.substring(2,4));
		datebuffer[2] = (byte)Integer.parseInt(rtimeString.substring(4,6));
		datebuffer[3] = (byte)Integer.parseInt(rtimeString.substring(6,8));
		datebuffer[4] = (byte)Integer.parseInt(rtimeString.substring(8,10));
		datebuffer[5] = (byte)Integer.parseInt(rtimeString.substring(10,12));
		byte[] rtimeByte =ByteUtil.bytesToDateByte(datebuffer);		
		
		dateByte[1]=(short)rtimeByte[0];
		dateByte[2]=(short)rtimeByte[1];
		dateByte[3]=(short)rtimeByte[2];
		dateByte[4]=(short)rtimeByte[3];
		dateByte[5]=(short)rtimeByte[4];
		dateByte[6]=(short)rtimeByte[5];


		return dateByte;
	}

	@Override
	public String translateData(byte[] datas,int len,int offset) throws ParseException {
        String stime = String.format("%02X",datas[offset+1])
           +"-"+String.format("%02X",datas[offset+2])
           +"-"+String.format("%02X",datas[offset+3])
           +" "+String.format("%02X",datas[offset+4])
           +":"+String.format("%02X",datas[offset+5])
           +":"+String.format("%02X",datas[offset+6]);	  

        Date rtime=null;

	      rtime = DateTimeUtil.YYYYMMddHHmmss().parse("20"+stime);


		return DateTimeUtil.YYYYMMddHHmmss().format(rtime);
	}

	@Override
	public String encode(String pvalue, int length) throws ParseException {
		return ef().format(df().parse(pvalue));

	}

	@Override
	public String decode(String pdata, int length) throws ParseException {
		return df().format(ef().parse(pdata));

	}

	@Override
	public Date parseValue(String pvalue) throws ParseException {
		return df().parse(pvalue);

	}

}
